from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from spit.models import Spit


class SpitSerializer(serializers.ModelSerializer):
    userid = serializers.IntegerField(label='用户id', read_only=True)
    hasthumbup = serializers.BooleanField(label='是否已经点赞', read_only=True)
    collected = serializers.BooleanField(label='是否已经收藏', read_only=True)
    class Meta:
        model = Spit
        fields = '__all__'
        extra_kwargs = {'user': {'required': False},
                        'parent': {'required': False}}

    def create(self, validated_data):
        request = self.context.get('request')

        try:
            user = request.user
        except:
            user = None

        spit = Spit()
        spit.content = request.data.get('content', '')
        # 判断是否是吐槽别人的吐槽
        if request.data.get('parent', None):
            # 判断是否登陆
            if user and user.is_authenticated:
                spit.user = user
                spit.nickname = user.nickname if user.nickname else user.username
                spit.avatar = user.avatar
                spit.parent = Spit.objects.get(id=request.data.get('parent'))
                spit.parent.comment += 1
                spit.parent.save()
                spit.userid = str(user.id)
        spit.save()
        return spit
